package io.simple.core;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

/**
 * @version 0.1
 * access source for simple developer
 */
public class SourceSearcher {

    private File sourceRoot;
    private static SourceSearcher searcher;
    private  List<SourceHandle> handles = new LinkedList<SourceHandle>();

    private SourceSearcher(){}

    public static SourceSearcher getInstance() {
        if(searcher == null) {
            searcher = new SourceSearcher();
        }
        return searcher;
    }


    /**
     *
     * @param handle
     * @return SourceSearcher
     */
    public static SourceSearcher addHandle(SourceHandle handle){
        getInstance().handles.add(handle);
        return getInstance();
    }

    /**
     * simple boot
     */
    public static void boot(){
        getInstance().loopSource(searcher.getSourceRoot());
    }

    private static File getSourceRoot(){
        String rootDir = Thread.currentThread().getContextClassLoader().getResource(".").getPath();
        getInstance().sourceRoot = new File(rootDir);
        return getInstance().sourceRoot;
    }

    private void loopSource(File source){
        if(source.isDirectory()) for (File child: source.listFiles()) loopSource(child);
        else handleSource(source);
    }

    private void handleSource(File source){
        for (SourceHandle handle: handles) handle.handle(source);
    }
}
